﻿using System;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.API.Application.Models;
using Casamiel.API.Application.Services;
using Casamiel.Application;
using Casamiel.Common.Extensions;
using Casamiel.Domain;
using Casamiel.Domain.Entity;
using MediatR;

namespace Casamiel.API.Application.Commands
{
    /// <summary>
    /// Bind member card command handler.
    /// </summary>
    public sealed class BindMemberCardCommandHandler
        : BaseCommandHandler, IRequestHandler<BindMemberCardCommand, Zmodel>
    {
        /// <summary>
        /// Initializes a new instance of the
        /// <see cref="T:Casamiel.API.Application.Commands.BindMemberCardCommandHandler"/> class.
        /// </summary>
        /// <param name="iicApiService">Iic API service.</param>
        /// <param name="memberCard">Member card.</param>
        /// <param name="memberService"></param>
        /// <param name="mobileCheckCode">Mobile check code.</param>
        /// <param name="userLogService">User log service.</param>
        public BindMemberCardCommandHandler(IIcApiService iicApiService,
            IMemberCardService memberCard, IMemberService memberService,
                                            IMobileCheckCode mobileCheckCode, IUserLogService userLogService) : base(iicApiService, memberCard, memberService, mobileCheckCode, userLogService)
        {

        }
        /// <summary>
        /// Handle the specified request and cancellationToken.
        /// </summary>
        /// <returns>The handle.</returns>
        /// <param name="request">Request.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        public async Task<Zmodel> Handle(BindMemberCardCommand request, CancellationToken cancellationToken)
        {
            if (request == null) {
                throw new ArgumentNullException(nameof(request));
            }

            var sucess = await MobileCheckCode.CheckSmsCodeAsync(request.Mobile, request.Yzm, false).ConfigureAwait(false);

            if (sucess["code"].ToString() != "0") {
                //obj["code"] = -2;
                //obj["msg"] = "验证码输入不正确!";
                return new Zmodel { code = sucess["code"].ToString().ToInt32(0), msg = sucess["msg"].ToString() };
            }
            var cardinfo = await MemberCardService.FindAsync<ICasaMielSession>(request.Cardno).ConfigureAwait(false);
            if (cardinfo != null && cardinfo.Mobile != request.Mobile) {
                return new Zmodel { code = 22, msg = "卡号与注册手机号码不符" };
            }

            var memberInfo = await MemberService.FindAsync<ICasaMielSession>(request.Mobile).ConfigureAwait(false);
            if (memberInfo == null) {
                memberInfo = new Member { Mobile = request.Mobile, Source = request.Source, CreateDate = DateTime.Now, LastLoginDate = DateTime.Now };
                await MemberService.AddAsync<ICasaMielSession>(memberInfo).ConfigureAwait(false);
            }

            var mcards = await MemberCardService.GetListAsync<ICasaMielSession>(request.Mobile).ConfigureAwait(false);
            var content = "";
            if (mcards == null) {

                var bandcard = await IcApiService.Icregist(request.Cardno, request.Mobile, request.Source).ConfigureAwait(false);
                if (bandcard != null) {
                    content = bandcard.content;
                    if (bandcard.code == 0 || bandcard.code == 101 || bandcard.code == 103) {
                        var mcard = new MemberCard {
                            M_ID = memberInfo.ID,
                            CardNO = request.Cardno,
                            Mobile = request.Mobile,
                            IsBind = true,
                            CardType = "1",
                            BindTime = DateTime.Now,
                            CreateTime = DateTime.Now,
                            State = 1,
                            Source = request.Source
                        };
                        try {
                            await MemberCardService.AddAsync<ICasaMielSession>(mcard).ConfigureAwait(false);
                        } catch (SqlException ex) {
                            if (ex.Number != 2627) {
                                throw;
                            }
                        }
                    } else {
                        return bandcard;
                    }
                } else {
                    return new Zmodel { code = -1, msg = "抱歉，请重试" };
                }
            } else {
                // var list = mcards.Where(c => c.CardType != "3" && c.IsBind == true);
                if (mcards.Any(c => c.CardType != "3" && c.IsBind == true)) {
                    return new Zmodel { code = -1, msg = "您已经绑过卡" };
                }
                var entity = await MemberCardService.FindAsync<ICasaMielSession>(request.Cardno, request.Mobile).ConfigureAwait(false);
                var bandcard = await IcApiService.Icregist(request.Cardno, request.Mobile, request.Source).ConfigureAwait(false);
                if (bandcard != null) {
                    content = bandcard.content;
                    if (bandcard.code == 0 || bandcard.code == 101 || bandcard.code == 103) {
                        if (entity == null) {
                            entity = new MemberCard {
                                M_ID = memberInfo.ID,
                                CardNO = request.Cardno,
                                Mobile = request.Mobile,
                                IsBind = true,
                                BindTime = DateTime.Now,
                                CardType = "1",
                                CreateTime = DateTime.Now,
                                Source = request.Source,
                                State = 1
                            };

                            try {
                                await MemberCardService.AddAsync<ICasaMielSession>(entity).ConfigureAwait(false);
                            } catch (SqlException ex) {
                                if (ex.Number != 2627) {
                                    return new Zmodel { code = 0, content = content, msg = "绑卡成功！" };
                                }
                            }
                            //await _memberCard.UnitOfWork.SaveEntitiesAsync();
                        } else {
                            entity.IsBind = true;
                            entity.BindTime = DateTime.Now;
                            entity.Source = request.Source;
                            await MemberCardService.UpdateAsync<ICasaMielSession>(entity).ConfigureAwait(false);
                            //await _memberCard.UnitOfWork.SaveChangesAsync();
                            // return new JsonResult(new { code = 0, content = "", msg = "绑卡成功！" });
                        }
                    } else {
                        return bandcard;
                    }
                }
                try {
                    var logdata = new UserLog { Url = request.RequestUrl, OPInfo = $"绑会员卡,卡号:[{request.Cardno}], 来源：{request.Source}", OPTime = DateTime.Now, UserName = request.Mobile, UserIP = request.UserIP };
                    //Task task = new Task(async () => {
                     await UserLogService.AddAsync<ICasaMielSession>(logdata).ConfigureAwait(false);
                    //});
                   // task.Start();
                } catch (AggregateException ex) {
                    foreach (var item in ex.InnerExceptions) {
                        Logger.Error(string.Format(CultureInfo.CurrentCulture, "异常类型：{0}{1}来自：  {2} {3} 异常内容：{4}", item.GetType(),
                    Environment.NewLine, item.Source,
                    Environment.NewLine, item.Message));

                    }

                    
                }
               
            }
            return new Zmodel { code = 0, content = content, msg = "绑卡成功！" };
        }
    }
}
